package edu.gyc.hisecurity.auth;

import com.fasterxml.jackson.databind.ObjectMapper;
import edu.gyc.hisecurity.model.ResultBean;
import edu.gyc.hisecurity.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;

    @Bean
   public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
      /**  auth.inMemoryAuthentication()
                .withUser("zyj")
                .password("123")
                .roles("admin")
                .and()
                .withUser("周慧敏")
                .password("123")
                .roles("lover");
       */
      auth.userDetailsService(userService);
    }

    @Bean
    RoleHierarchy roleHierarchy() { //角色继承，ROLE_dba > ROLE_admin dba权限大于admin
        RoleHierarchyImpl roleHierarchy=new RoleHierarchyImpl();
        String hierarchy = "ROLE_dba > ROLE_admin \n ROLE_admin > ROLE_lover";
        roleHierarchy.setHierarchy(hierarchy);
        return roleHierarchy;
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/girl/**").hasRole("admin")
                // .antMatchers("/lover/**").hasAnyRole("admin", "lover")
                .antMatchers("/lover/**").access("hasAnyRole('lover')")
                .antMatchers("/admin").hasRole("admin")
                .antMatchers("/lover","/love").hasRole("lover")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginProcessingUrl("/doLogin")
                .loginPage("/login")
                .successHandler(new AuthenticationSuccessHandler() { //前后端分离用，传统用successForwardUrl()
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                        response.setContentType("application/json;charset=utf-8");
                        PrintWriter out=response.getWriter();
                        ResultBean resultBean = new ResultBean(200, authentication.getPrincipal());
                        out.write(new ObjectMapper().writeValueAsString(resultBean));
                        out.flush();
                        out.close();
                    }
                })
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                                        AuthenticationException e) throws IOException, ServletException {
                        response.setContentType("application/json;charset=utf-8");
                        PrintWriter out=response.getWriter();
                        ResultBean resultBean = new ResultBean(401, "Error");
                        if (e instanceof BadCredentialsException) {
                            resultBean.setMsg("用户名密码错误,BeCareful");
                        } else if (e instanceof LockedException) {
                            resultBean.setMsg("账号锁定！");
                        }

                        out.write(new ObjectMapper().writeValueAsString(resultBean));
                        out.flush();
                        out.close();
                    }
                })
                .permitAll()
                .and()
                .logout()
                .logoutSuccessHandler(new LogoutSuccessHandler() {
                    @Override
                    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                        response.setContentType("application/json;charset=utf-8");
                        PrintWriter out=response.getWriter();
                        ResultBean resultBean = new ResultBean(200, "注销成功");
                        out.write(new ObjectMapper().writeValueAsString(resultBean));
                        out.flush();
                        out.close();
                    }
                })
                .and()
                .csrf().disable();
    }
}
